package com.environment_pro.monitor.controller;

import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.environment_pro.monitor.model.TbLogLogin;
import com.environment_pro.monitor.model.TbLogOperate;
import com.environment_pro.monitor.model.TbSystemConf;
import com.environment_pro.monitor.model.TbSystemUser;
import com.environment_pro.monitor.service.TbLogLoginService;
import com.environment_pro.monitor.service.TbLogOperateService;
import com.environment_pro.monitor.service.TbSystemConfService;
import com.environment_pro.monitor.service.TbSystemUserService;
import com.environment_pro.monitor.util.StaticUtil;
import com.environment_pro.monitor.util.PageInfo;

@Controller
@RequestMapping("/base")
public class BaseController {
	
	private static final Logger logger = Logger.getLogger(BaseController.class);
	
	protected PageInfo pageInfo = new PageInfo();
	

	@Autowired
	private TbLogOperateService tbLogOperateService;
	
	
	@Autowired
	private TbSystemUserService tbSystemUserService;
	
	@Autowired
	private TbLogLoginService tbLogLoginService;
	
	@Autowired
	private TbSystemConfService tbSystemConfService;
	
	/**
	 * 登录
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletRequest request){
		//已经登录
		String loginname  = StaticUtil.null2String(request.getSession().getAttribute("loginname"));
		if (loginname!=null && loginname.length()>1) { 
			logger.info(loginname + "====login====");
			return "redirect:/base/index";
        } else {  
        	//登录验证
        	loginname  = StaticUtil.null2String(request.getParameter("loginname"));
        	if (loginname!=null && loginname.length()>1) { 
        		//tbSystemUserService=(TbSystemUserService) StaticUtil.getBean("tbSystemUserService");
        		TbSystemUser tbSystemUser = tbSystemUserService.findByUsername(loginname);
        		request.getSession().setAttribute("LoginTbSystemUser",tbSystemUser);
        		request.getSession().setAttribute("loginname", loginname);
        		logger.info(loginname + "==login==");
        		saveLogLogin(request, tbSystemUser);
    			return "redirect:/base/index";
        	}else {  
        		//返回登录页面
        		return "/login"; 
        	}
        }
	}

	/**
	 * 保存登录日志
	 * @param request
	 * @param tbSystemUser
	 */
	private void saveLogLogin(HttpServletRequest request, TbSystemUser tbSystemUser) {
		//保存登录日志
		TbLogLogin o = new TbLogLogin();
		o.setLoginDate(new Date());
		o.setLoginSessionId(request.getSession().getId());
		o.setLoginIp(request.getRemoteAddr());//获得客户端的IP地址 
		o.setLoginHostName(request.getRemoteHost());//获得客户端电脑的名字
		o.setLoginUserAgent(request.getHeader("User-agent"));//返回客户端浏览器的版本号、类型
		o.setUserId(tbSystemUser.getId());
		o.setRealName(tbSystemUser.getRealName());
		o.setUsername(tbSystemUser.getUsername());
		tbLogLoginService.save(o);
	}
	
	/**
	 * 初始化分页参数
	 * @param request
	 */
	protected void initPageParameter(HttpServletRequest request) {
		
		//处理分页参数
		Integer curPage = StaticUtil.null2Integer(request.getParameter("curPage"));
		curPage = curPage>0?curPage:1;
		
		Integer pageSize = StaticUtil.null2Integer(request.getParameter("pageSize"));
		TbSystemConf pageSizeConf = tbSystemConfService.findByKeyName("app.pager.pageSize");
		pageSize = pageSize>0?pageSize:StaticUtil.null2Integer(pageSizeConf.getKeyValue());
		
		Integer totalCount = StaticUtil.null2Integer(request.getParameter("totalCount"));
		
		Long totalCountTimeMillis = StaticUtil.null2Long(request.getParameter("totalCountTimeMillis"));
		
		TbSystemConf totalCountTimeoutConf = tbSystemConfService.findByKeyName("app.pager.totalCountTimeout");
		Integer totalCountTimeout = StaticUtil.null2Integer(totalCountTimeoutConf.getKeyValue());
		
		pageInfo.setCurPage(curPage);
		pageInfo.setPageSize(pageSize);
		pageInfo.setTotalCount(totalCount);
		pageInfo.setTotalCountTimeMillis(totalCountTimeMillis);
		pageInfo.setTotalCountTimeout(totalCountTimeout);
		
		logger.debug("初始化分页参数完成");
	}
	
	/**
	 * 首页
	 * @param request
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request){
		String loginname  = StaticUtil.null2String(request.getSession().getAttribute("loginname"));
		//logger.info(loginname + "==index==");
		return "/index";
	}
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request){
		String loginname  = StaticUtil.null2String(request.getSession().getAttribute("loginname"));
		logger.info(loginname + "==logout==");
		request.getSession().invalidate();
		return "/login";
	}
	
	/**
	 * 登出
	 * @param request
	 * @return
	 */
	@RequestMapping("/test")
	public String test(HttpServletRequest request){
		return "/modal";
	}
	
	/**
	 * 保存操作日志
	 * @param request
	 * @param Content
	 */
	protected void saveLogOperate(HttpServletRequest request,String Content) {
		//保存日志
		TbSystemUser u = (TbSystemUser) request.getSession().getAttribute("LoginTbSystemUser");
		//u= new TbSystemUser();
		TbLogOperate t = new TbLogOperate();
		t.setLoginSessionId(request.getSession().getId());
		t.setJobNumber(u.getJobNumber());
		t.setUserId(u.getId());
		t.setUsername(u.getUsername());
		t.setRealName(u.getRealName());
		t.setOperateTime(new Date());
		t.setOperateUrl(request.getRequestURI());
		t.setOperatePara(this.getAllRequstAttribute(request));
		t.setOperateContent(Content);
		tbLogOperateService.save(t);
	}


	/**
	 * 获取所有请求参数
	 * @param request
	 * @return
	 */
	private String getAllRequstAttribute(HttpServletRequest request) {
		String result = "";
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			for(Enumeration<?> e  =  request.getParameterNames(); e.hasMoreElements();)   {
				Object o  =  e.nextElement();
				map.put((String) o, request.getParameter((String) o));
			}
			result =  map.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug(result);
		return result;
	}
	
}
